//
//  NSDate+Extension.swift
//  WeiboDateTest
//
//  Created by stevenSu on 15/8/10.
//  Copyright © 2015年 stevenSu. All rights reserved.
//

import UIKit

extension NSDate {
    
    class func inputDate(string: String) -> NSDate? {
        let dateformat = NSDateFormatter()
        dateformat.locale = NSLocale(localeIdentifier: "en")
        dateformat.dateFormat = "EEE MMM dd HH:mm:ss zzz yyyy"
        return dateformat.dateFromString(string)
    }
    
    ///     -   刚刚(一分钟内)
    ///     -   X分钟前(一小时内)
    ///     -   X小时前(当天)
    
    ///     -   昨天 HH:mm(昨天)
    ///     -   MM-dd HH:mm(一年内)
    ///     -   yyyy-MM-dd HH:mm(更早期)
    var dateDescription: String {
        let cal = NSCalendar.currentCalendar()
        if cal.isDateInToday(self) {
            // 今天
            let timeinterval = Int(NSDate().timeIntervalSinceDate(self))
            switch timeinterval {
            case 0..<60: return "刚刚"
            case 60..<3600: return "\(timeinterval / 60)分钟前"
            default: return "\(timeinterval / 3600)小时前"
            }
        } else {
            // 不是今天
            var dateString = " HH:mm"
            if cal.isDateInYesterday(self) {
                dateString = "昨天" + dateString
            } else if cal.compareDate(self, toDate: NSDate(), toUnitGranularity: NSCalendarUnit.Year) == NSComparisonResult.OrderedSame { // 比较是否一年内不精确到秒，else cal.components
                dateString = "MM-dd" + dateString
            } else {
                dateString = "yyyy-MM-dd" + dateString
            }
            let dateformat = NSDateFormatter()
            dateformat.dateFormat = dateString
            return dateformat.stringFromDate(self)
        }
    }
}
